#include"heap.h"

void Heap_Init(HP* php)
{
	php->data = NULL;
	php->size = 0;
	php->capacity = 0;
}
void Heap_Destory(HP* php)
{
	assert(php);
	free(php->data);
	php->data = NULL;
	php->size = 0;
	php->capacity = 0;
}

void Swap(Heapdatatype* a, Heapdatatype* b)
{
	Heapdatatype tmp = *a;
	*a = *b;
	*b = tmp;
}
void Heap_Push(HP* php, Heapdatatype x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int newCapacity = (php->capacity == 0 ? 4 : 2 * php->capacity);
		Heapdatatype* tmp = (Heapdatatype*)realloc(php->data,newCapacity * sizeof(Heapdatatype));
		if (tmp == NULL)
		{
			perror("malloc failed");
			exit(-1);
		}
		php->data = tmp;
		php->capacity = newCapacity;
	}
	php->data[php->size++] = x;
	AdjustUp(php->data, php->size - 1);
}
void AdjustUp(Heapdatatype* a, int child)
{
	int parent = (child  - 1)/2;
	while (child > 0)
	{
		if (a[parent] < a[child])
		{
			Swap(&a[parent], &a[child]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void Heap_Print(HP* php)
{
	assert(php);
	for (int i = 0; i < php->size; i++)
	{
		printf("%d   ", php->data[i]);
	}
	printf("\n");
}

void Heap_Pop(HP* php)
{
	assert(php);
	assert(php->size > 0);
	Swap(&php->data[0], &php->data[php->size-1]);
	php->size--;
	AdjustDown(php->data, 0, php->size);
}
void AdjustDown(Heapdatatype* a, int parent, int n)
{
	int child = parent * 2 + 1;
	while (child < n)
	{
		if (child + 1 < n && a[child] > a[child + 1])
		{
			child++;
		}
		if ( a[parent] > a[child] )
		{
			Swap(&a[parent], &a[child]);
			parent = child;
			child = parent * 2 + 1;

		}
		else
		{
			break;
		}
	}
}


bool Heap_Empty(HP* php)
{
	assert(php);
	return php->size == 0;
}
Heapdatatype HeapTop(HP* php)
{
	assert(php);
	assert(php->size>0);

	return php->data[0];
}

void Heap_Sort(int*a,int n)
{
	for (int i = (n - 1 -1 ) / 2; i >= 0; i--)
	{
		AdjustDown(a, i,n);
	}
	int end = n - 1;
	while (end > 0)
	{
		Swap(&a[0], &a[end]);
		AdjustDown(a, 0, end);
		end--;
	}
}